﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApp_consoleExec
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private CmdExecHelper cmd;
        private LogFileHelper log;

        private void ThreadingReadingConsole()
        {
            string console_input;
            while(true)
            {
                console_input = Console.ReadLine();
                log.WriteLine(console_input);
                if((cmd != null)&&(cmd.Started))
                {
                    cmd.WriteLine(console_input);
                }
                else
                {
                    Console.WriteLine(console_input);
                }
            }
        }

        private Thread threadGetConsole;

        private void button_StartExec_Click(object sender, EventArgs e)
        {
            log = new LogFileHelper(textBox_SaveLogPath.Text);
            cmd = new CmdExecHelper(textBox_ExecFilePath.Text, textBox_ExecArgs.Text);
            cmd.Received += Cmd_Received;
            cmd.Exited += Cmd_Exited;
            cmd.Start();
        }

        private void Cmd_Exited()
        {
            throw new NotImplementedException();
        }

        private void Cmd_Received(string s)
        {
            log.WriteLine(s);
            Console.WriteLine(s);
        }

        private void button_SaveFileDialog_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = "Text Files|*.txt|Log Files|*.log|All Files (*.*)|*.*";
            var result = sd.ShowDialog();
            if(result == DialogResult.OK)
            {
                textBox_SaveLogPath.Text = sd.FileName;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            threadGetConsole = new Thread(new ThreadStart(ThreadingReadingConsole));
            threadGetConsole.Start();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        private void button_StopExec_Click(object sender, EventArgs e)
        {
            if(cmd == null)
            {
                return;
            }
            if(!cmd.Started)
            {
                return;
            }
            cmd.Abort();
        }
    }
}
